package com.example.servicefeign.rule;


import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

public class CustomRule extends AbstractLoadBalancerRule {

    private static int count = 0;
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object key) {

        return choose(getLoadBalancer(), key);
    }

    public Server choose(ILoadBalancer loadBalancer, Object key) {
        if (null == loadBalancer) {
            return null;
        }

        Server server;
        List<Server> upServer = loadBalancer.getReachableServers();
        List<Server> allServer = loadBalancer.getAllServers();
        int upServerCount = upServer.size();
        int allServerCount = allServer.size();
        if (upServerCount == 0 || allServerCount == 0) {
            return null;
        }
        if (upServer.size() < 2) {
            return upServer.get(0);
        }
        count++;
        System.out.println(count);
        if (count < 2) {
            server = upServer.get(0);
        } else {
            server = upServer.get(1);
        }
        if (count >= 4) {
            count = 0;
        }
        return server;
    }
}
